//
//  ComposeViewController.swift
//  XDweibo
//
//  Created by HanXingda on 15/7/8.
//  Copyright © 2015年 韩兴达. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

private let maxTextLength = 140
class ComposeViewController: UIViewController,UITextViewDelegate {

    //记录toolBar的底部约束
    private var toolBarBottomCons: NSLayoutConstraint?
    
    /// 表情键盘控制器
    private lazy var emoticonKeyboardVC: EmoticonViewController = EmoticonViewController { [unowned self] (emoticon)  in
        self.textView.insertEmoticon(emoticon)
    }
    ///  切换表情视图
    func inputEmoticon() {
        // 如果输入视图是 nil，说明使用的是系统键盘
        print(textView.inputView)
        
        // 要切换键盘之前，需要先关闭键盘
        textView.resignFirstResponder()
        
        // 更换键盘输入视图
        textView.inputView = (textView.inputView == nil) ? emoticonKeyboardVC.view : nil
        
        // 重新设置焦点
        textView.becomeFirstResponder()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
        
        
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        //        view.endEditing(true)
        textView.resignFirstResponder()
    }
    
    func cancelBtnClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
      func pushMessageBtnClick() {
        print(__FUNCTION__)
        //判断是否有内容
        if textView.emoticonText().characters.count <= 0 {
            return
        }
        //判断是否够长
       if textView.emoticonText().characters.count > maxTextLength {
            SVProgressHUD.showInfoWithStatus("文本内容过长", maskType: SVProgressHUDMaskType.Black)
            return
        }
        NetWorkTools.sharedNetworkTools().postStatusMessage(textView.emoticonText()) { (error) -> () in
            if error != nil {
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            //发布成功
            self.cancelBtnClick()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    var localKeyBoardFlag = false
    func keyBoardChange(notification: NSNotification) {
        print(notification)
        let rect = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        let localKey = notification.userInfo!["UIKeyboardIsLocalUserInfoKey"]!.boolValue
        var duration = notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue
        
        if !localKey {
            localKeyBoardFlag = true
            return
        }
        
        duration = localKeyBoardFlag ? 0 : duration
        localKeyBoardFlag = false
        
        
        toolBarBottomCons?.constant = -(view.bounds.height - rect.origin.y)
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK:- UITextview代理方法
    func textViewDidChange(textView: UITextView) {
        
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        //判断文字长度
        
        let len = maxTextLength - textView.emoticonText().characters.count
        lengthLabel.text = len == 0 ? "" : String(len)
        lengthLabel.textColor = len > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
    
    
    
    // MARK: - 准备UI
    override func loadView() {
        super.loadView()
        view.backgroundColor = UIColor.whiteColor()
        
        // 1. 添加子控制器
        addChildViewController(emoticonKeyboardVC)
        // 2. 准备UI
        prepareUI()
        
    }

    func prepareUI() {
        prepareToolBar()
        prepareNavBar()
        prepareTextView()
        prepareOtherUI()
    }
        func prepareToolBar() {
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]

        //所有按钮的数组
        var items = [UIBarButtonItem]()
        
        //遍历设置数组
        for dict in itemSettings {
            
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, hightImageName: nil, target: nil, action: dict["action"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolBar.items = items
        
        view.addSubview(toolBar)
        //布局
        
       let cons =  toolBar.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: nil)


    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subView" : toolBar]))
       toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
    }
    
    func prepareTextView() {
        textView.delegate = self
        view.addSubview(textView)
        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        textView.ff_AlignInner(ff_AlignType.TopRight, referView: view, size: nil)
        textView.ff_AlignVertical(ff_AlignType.TopLeft, referView: toolBar, size: nil)
        
        textView.font = UIFont.systemFontOfSize(18)
        
        textView.alwaysBounceVertical = true
        
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        placeHolderLabel.text = "分享新鲜事。。。"
        
        placeHolderLabel.hidden = false
        
        placeHolderLabel.sizeToFit()
        
        textView.addSubview(placeHolderLabel)
        
        placeHolderLabel.ff_AlignInner(ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    
    func prepareNavBar() {
        //左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBtnClick")
        //右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "pushMessageBtnClick")
        navigationItem.rightBarButtonItem?.enabled = false
        //导航栏
        let titleView = UIView(frame: CGRectMake(0, 0, 100, 32))
        let label1 = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        label1.text = "发微博"
        label1.sizeToFit()
        let label2 = UILabel(color: UIColor(white: 0.0, alpha: 0.5), fontSize: 13)
        label2.text = sharedUserAccount?.name ?? ""
        label2.sizeToFit()
        
        titleView.addSubview(label1)
        titleView.addSubview(label2)
        
        label1.ff_AlignInner(ff_AlignType.TopCenter, referView: titleView, size: nil)
        label2.ff_AlignInner(ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
        
    }
    
    func prepareOtherUI() {
        view.addSubview(lengthLabel)
        lengthLabel.text = "140"
        lengthLabel.textColor = UIColor.lightGrayColor()
        lengthLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -12, y: -12))
    }
    // MARK: - 懒加载
    
    //文字输入框
    private lazy var textView = UITextView()
    
    private lazy var lengthLabel = UILabel()
    
    private lazy var toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: 44))
    
    private lazy var placeHolderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
}
